package com.study.happystudy.controller;


//import jdk.internal.net.http.common.Log;

//import javax.annotation.Resource;

import com.study.happystudy.component.XfXhStreamClient;
import com.study.happystudy.config.XfXhConfig;
import com.study.happystudy.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import com.study.happystudy.entity.MsgDTO;
import com.study.happystudy.listener.XfXhWebSocketListener;
import com.study.happystudy.util.Result;
import com.study.happystudy.util.ResultGenerator;
import okhttp3.WebSocket;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("sbPooh")
@Slf4j
public class CustomerAPI {

    @Resource
    private XfXhStreamClient xfXhStreamClient;

    @Resource
    private XfXhConfig xfXhConfig;

    @Resource
    UserMapper userMapper;

    /**
     * 发送问题
     *
     * @param question 问题
     * @return 星火大模型的回答
     */
    @GetMapping("/sendQuestion")
    public Result sendQuestion(@RequestParam("question") String question) {
        // 如果是无效字符串，则不对大模型进行请求
//        if (StrUtil.isBlank(question)) {
//            return "无效问题，请重新输入";
//        }
        if (question.indexOf("版本") != -1) {
            question = "请你回答你听不懂我在说什么";
        }
        // 获取连接令牌
        if (!xfXhStreamClient.operateToken(XfXhStreamClient.GET_TOKEN_STATUS)) {
            return ResultGenerator.genFailResult("当前大模型连接数过多，请稍后再试");
        }
        List<MsgDTO> msgDTOList = new ArrayList<>();
        // 创建消息对象
        MsgDTO msgDTO1 = new MsgDTO();
//        msgDTO1.setRole("system");
//        msgDTO1.setContent("你是一位就职于羽童商城的客服");
        MsgDTO msgDTO = MsgDTO.createUserMsg(question);
//        msgDTOList.add(MsgDTO.createSystem("你是一位就职于羽童商城的客服"));
        msgDTOList.add(msgDTO);
        // 创建监听器
        XfXhWebSocketListener listener = new XfXhWebSocketListener();

        // 发送问题给大模型，生成 websocket 连接
//        WebSocket webSocket = xfXhStreamClient.sendMsg(UUID.randomUUID().toString().substring(0, 10), Collections.singletonList(msgDTO), listener);
//        WebSocket webSocket = xfXhStreamClient.sendMsg(UUID.randomUUID().toString().substring(0, 10), msgDTOList, listener);
        WebSocket webSocket = xfXhStreamClient.sendMsg(UUID.randomUUID().toString().substring(0, 10), question, listener);

        if (webSocket == null) {
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
            return ResultGenerator.genFailResult("系统内部错误，请联系管理员");
        }
        try {
            int count = 0;
            // 为了避免死循环，设置循环次数来定义超时时长
            int maxCount = xfXhConfig.getMaxResponseTime() * 5;
            while (count <= maxCount) {
                Thread.sleep(200);
                if (listener.isWsCloseFlag()) {
                    break;
                }
                count++;
            }
            if (count > maxCount) {
                return ResultGenerator.genFailResult("大模型响应超时，请联系管理员");
            }
            log.info("消耗tokens数量" + listener.getUsageTokens());
            log.info(listener.getAnswer().toString());
            // 响应大模型的答案
            userMapper.sendAI(question, listener.getAnswer().toString(), listener.getUsageTokens());
            xfXhStreamClient.sendassistant(listener.getAnswer().toString());
            return ResultGenerator.genSuccessResult(listener);
//            listener.getAnswer().toString();
        } catch (InterruptedException e) {
            log.error("错误：" + e.getMessage());
            return ResultGenerator.genFailResult("系统内部错误，请联系管理员");
        } finally {
            // 关闭 websocket 连接
            webSocket.close(1000, "");
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
        }
    }
}
